package com.java.system.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.java.common.exception.BusinessExceptionEnum;
import com.java.common.exception.RRException;
import com.java.common.utils.CopyUtil;
import com.java.common.utils.PageUtils;
import com.java.common.utils.Query;
import com.java.common.utils.UuidUtil;
import com.java.system.dao.UserDao;
import com.java.system.entity.Resource;
import com.java.system.entity.User;
import com.java.system.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Map;

@Service("userService")
@Slf4j
public class UserServiceImpl extends ServiceImpl<UserDao, User> implements UserService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<User> page = this.page(
                new Query<User>().getPage(params),
                // 拼接查询条件
                new LambdaQueryWrapper<User>()
        );

        return new PageUtils(page);
    }

    @Override
    public void updateOrSave(User user) {
        if (StrUtil.isNotBlank(user.getId())) {
            user.setPassword(null);
            updateById(user);
        } else {
            user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
            User userDb = this.selectByLoginName(user.getLoginName());
            if (userDb != null) {
                throw new RRException(BusinessExceptionEnum.USER_LOGIN_NAME_EXIST.getDesc());
            }
            user.setId(UuidUtil.getShortUuid());
            save(user);
        }
    }

    /**
     * 根据登录名查询用户信息
     */
    public User selectByLoginName(String loginName) {
        return this.getOne(new LambdaQueryWrapper<User>().eq(User::getLoginName, loginName));
    }

    /**
     * 重置密码
     */
    public void restPassword(User user) {
        user.setPassword(DigestUtils.md5DigestAsHex(user.getPassword().getBytes()));
        this.updateById(user);
    }

    /**
     * 登录
     */
    public User login(User user) {
        User userDb = selectByLoginName(user.getLoginName());
        if (userDb == null) {
            log.info("用户名不存在, {}", user.getLoginName());
            throw new RRException(BusinessExceptionEnum.LOGIN_USER_ERROR.getDesc());
        } else {
            if (userDb.getPassword().equals(user.getPassword())) {
                // 为登录用户读取权限
                setAuth(userDb);
                user.setPassword(null);
                return userDb;
            } else {
                log.info("密码不对, 输入密码：{}, 数据库密码：{}", user.getPassword(), userDb.getPassword());
                throw new RRException(BusinessExceptionEnum.LOGIN_USER_ERROR.getDesc());
            }
        }
    }

    /**
     * 为登录用户读取权限
     */
    private void setAuth(User loginUser) {
        List<Resource> resourceDtoList = this.baseMapper.findResources(loginUser.getId());
        loginUser.setResources(resourceDtoList);

        // 整理所有有权限的请求，用于接口拦截
        HashSet<String> requestSet = new HashSet<>();
        if (!CollectionUtils.isEmpty(resourceDtoList)) {
            for (Resource resourceDto : resourceDtoList) {
                String arrayString = resourceDto.getRequest();
                List<String> requestList = JSON.parseArray(arrayString, String.class);
                if (!CollectionUtils.isEmpty(requestList)) {
                    requestSet.addAll(requestList);
                }
            }
        }
        log.info("有权限的请求：{}", requestSet);
        loginUser.setRequests(requestSet);
    }


}